const path = require('path');
const webpack = require('webpack');
const {merge} = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {spawn} = require('child_process');
const webpackBaseConfig = require('./webpack.common');

const port = process.env.PORT || 8080;
const publicPath = `http://localhost:${port}/dist`;

const hot = [
  'react-hot-loader/patch',
  `webpack-dev-server/client?http://localhost:${port}/`,
  'webpack/hot/only-dev-server',
];

// 多页面配置
// const entry = {
//   index: hot.concat(require.resolve('./src/renderer/index/index.tsx')),
//   userInfo: hot.concat(require.resolve('./src/renderer/userInfo/index.tsx'))
// };

// const htmlWebpackPlugin = Object.keys(entry).map(name => new HtmlWebpackPlugin({
//   inject: 'body',
//   scriptLoading: 'defer',
//   template: path.join(__dirname, '../public/index.html'),
//   minify: false,
//   filename: `${name}.html`,
//   chunks: [name]
// }));

const htmlWebpackPlugin = new HtmlWebpackPlugin({
  inject: 'body',
  scriptLoading: 'defer',
  template: path.join(__dirname, '../public/index.html'),
  minify: false,
  filename: `index.html`,
});

module.exports = merge(webpackBaseConfig, {
  devtool: 'inline-source-map',
  mode: 'development',
  target: 'electron-renderer',
  entry: {
    renderer: [
      require.resolve('../src/renderer/index.js'),
      // 'react-hot-loader/patch',
      `webpack-dev-server/client?http://localhost:${port}/`,
      'webpack/hot/only-dev-server',
    ],
  },
  output: {
    publicPath,
    filename: '[name].dev.js'
  },
  plugins:[
    new webpack.HotModuleReplacementPlugin(), // hot module replacement 启动模块热替换的插件
    new webpack.EnvironmentPlugin({
      NODE_ENV: 'development',
    }),
    new webpack.LoaderOptionsPlugin({
      debug: true,
    }),
    htmlWebpackPlugin,
  ],
  devServer: {
    port,
    publicPath,
    compress: true,
    noInfo: false,
    stats: 'errors-only',
    inline: true,
    lazy: false,
    hot: true,
    headers: {'Access-Control-Allow-Origin': '*'},
    contentBase: path.join(__dirname, '../dist'),
    watchOptions: {
      aggregateTimeout: 300,
      ignored: /node_modules/,
      poll: 100
    },
    historyApiFallback: {
      verbose: true,
      disableDotRule: false
    },
    before() {
      // 启动渲染进程后执行主进程打包
      console.log('start main process...');
      spawn('npm', ['run', 'dev-main'], {
        shell: true,
        env: process.env,
        stdio: 'inherit'
      }).on('close', code => process.exit(code))
        .on('error', spawnError => console.error(spawnError));
    }
  }
});
